package org.lalib.controller.action;

import java.util.List;

import org.lalib.acquire.IControllerAction;
import org.lalib.controller.form.CUserForm;
import org.lalib.controller.service.CCategoryService;
import org.lalib.controller.service.CUserGroupService;
import org.lalib.controller.service.CUserService;
import org.lalib.entity.object.EUser;
import org.lalib.entity.object.EUserGroup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

@Scope(value = "request")
@Controller(value = "cUserAction")
public class CUserAction implements IControllerAction {

	private static final long serialVersionUID = 1L;

	@Autowired
	CCategoryService cCategoryService;

	@Autowired
	CUserGroupService cUserGroupService;

	@Autowired
	CUserService cUserService;

	@Autowired
	CUserForm cUserForm;

	public String init() {
		List<EUserGroup> allUserGroups = cUserGroupService.getAllUserGroups();
		cUserForm.setUserGroupList(allUserGroups);
		cUserForm.setUserGroupSelectItemList(cUserGroupService.getSelectItemListForUserGroup(allUserGroups));
		cUserForm.setUsers(getAllUsers());
		return "userDefination";
	}

	public void save() {
		EUser user = cUserForm.getUser();
		Long selectedUserGroupId = cUserForm.getSelectedUserGroupId();
		cUserService.save(user, selectedUserGroupId);
		cUserForm.clear();
		cUserForm.setUsers(getAllUsers());
	}

	public void delete(EUser user) {
		user = (EUser) cUserService.getUserById(user.getId());
		cUserService.delete(user);
		cUserForm.setUsers(getAllUsers());
	}

	private List<EUser> getAllUsers() {
		return cUserService.getAllUsers();
	}
}